package com.ojoin.trade.common.web.listener;

import java.util.Map;

import javax.servlet.ServletContextEvent;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.JedisPubSub;

import com.ojoin.trade.common.autoconfig.api.IChangeListener;
import com.ojoin.trade.common.autoconfig.base.ChangeableConfig;
import com.ojoin.trade.common.utils.JedisUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.SpringUtils;

public class WebContextListener extends org.springframework.web.context.ContextLoaderListener {
	
	private final static Logger log=LoggerFactory.getLogger(WebContextListener.class);
	
	@Override
	public void contextInitialized(ServletContextEvent event) {
		 super.contextInitialized(event);
		 
		 final ChangeableConfig config = SpringUtils.getBean(ChangeableConfig.class);
		 
		 Map<String,IChangeListener> listener=SpringUtils.getAbstractType(IChangeListener.class);
		 for (IChangeListener value : listener.values()) {
			 config.addListener(value);
			}
		 
		 
		 Thread configThread=new Thread(new Runnable(){
			@Override
			public void run() {
				JedisUtils.subscriber("online.config",new JedisPubSub(){
					@Override
					public void onMessage(String channel, String message) {
						LogUtils.info(log,"online.config receive update message");
						config.notifyListeners();
					}
					@Override
					public void onPMessage(String pattern, String channel,
							String message) {
					}
					@Override
					public void onSubscribe(String channel, int subscribedChannels) {
						LogUtils.info(log,"online.config begin Subscribe message");
					}
					@Override
					public void onUnsubscribe(String channel, int subscribedChannels) {
						LogUtils.info(log,"online.config end Subscribe message");
					}
					@Override
					public void onPUnsubscribe(String pattern, int subscribedChannels) {
					}
					@Override
					public void onPSubscribe(String pattern, int subscribedChannels) {
					}
				 }); 
			}
			 
		 },"online.config-Thread");
		 configThread.setDaemon(true);
		 configThread.start();
		 
	}
}